<?php
class Finance extends MY_Agent_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $page = intval($this->input->get_post('page'));
    	$page = $page ? $page : 1;
    	
    	$where = array('uid'=>$this->uInfo['uid']);
    	
        $this->load->model('finance/model_finance_withdrawals','finance_withdrawals');
        $total_rows = $this->finance_withdrawals->count($where);

        //分页
        $this->load->library('pagination');
         
        $config['total_rows'] = $total_rows;
        $config['per_page'] = 20;
        $config['base_url'] = '/finance/index';
         
        $this->pagination->initialize($config);
        $page_html = $this->pagination->create_links();
        
        //读取数据
        $offset = ($page-1) * $config['per_page'];
        
        $lists = $this->finance_withdrawals->lists($offset,  $config['per_page'], $where);


        $data = array(
            'lists' => $lists,
            'page_html'   => $page_html,
        	'total_num'  => $config['total_rows'],
        );
        $this->load->view('agent/finance/index', $data);
    }

    public function withdrawals()
    {
    	$this->load->model('finance/Model_finance_user_capital_account', 'fuca');
    	$capital_account = $this->fuca->capital_account_by_uid($this->uInfo['uid'], CURRENCY_SGD);
        $capital_account = $capital_account['data']['balance'];
        
    	$this->load->view('agent/finance/withdrawals', array('capital_account'=>$capital_account));
    }
    
    public function apply()
    {
        $amount = $this->input->get_post('amount');

    	//检测余额
        $this->load->model('finance/Model_finance_user_capital_account', 'fuca');
        $check_balance_rs = $this->fuca->check_balance($this->uInfo['uid'], $amount, CURRENCY_SGD);
        if (200 != $check_balance_rs['status'])
        {
            $this->jump($check_balance_rs['status']);
        }


        $this->load->model('finance/Model_finance_withdrawals', 'fw');
        $record_rs = $this->fw->record(0, $this->uInfo['uid'], $amount);
        if (200 != $record_rs['status'])
        {
            $this->jump($record_rs['status']);
        }


        //支出费用
        $this->load->model('finance/Model_finance_base_log', 'fbl');
        $defray_rs = $this->fbl->defray
        (
            $this->uInfo['uid'],
            $amount,
            CURRENCY_SGD,
            $record_rs['data']['cid'],
            '用户提现',
            'DEFRAY_WITHDRAWALS',
            FINANCE_BUSINESS_WITHDRAWALS,
            '用户提现'
        );


        if (200 != $defray_rs['status'])
        {
            $this->jump($defray_rs['status']);
        }

        $this->load->helper('url');
        redirect(url('agent').'anchor/index', 'refresh');
    }
}
